package com.colabo.j2ee.web.oaf.orgnization.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.colabo.j2ee.web.core.dictionary.CodeInfoCache;
import com.colabo.j2ee.web.core.dictionary.IPCodeInfoVO;
import com.colabo.j2ee.web.core.exception.CommonException;
import com.colabo.j2ee.web.core.exception.ServiceException;
import com.colabo.j2ee.web.core.persistence.HqlWrapper;
import com.colabo.j2ee.web.core.servertime.IServerTime;
import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;
import com.colabo.j2ee.web.core.util.DateTimeUtil;
import com.colabo.j2ee.web.core.util.PropertyUtil;
import com.colabo.j2ee.web.core.util.StringUtil;
import com.colabo.j2ee.web.core.vo.SessionUserHolder;
import com.colabo.j2ee.web.core.vo.RecordObject;
import com.colabo.j2ee.web.oaf.common.AppConstants;
import com.colabo.j2ee.web.oaf.monitorperspective.ILogDataService;
import com.colabo.j2ee.web.oaf.orgnization.IUnitService;
import com.colabo.j2ee.web.oaf.orgnization.UnitCache;
import com.colabo.j2ee.web.oaf.orgnization.model.IPBizTypeVO;
import com.colabo.j2ee.web.oaf.orgnization.model.SCUnitProfileVO;
import com.colabo.j2ee.web.oaf.security.IDataPermissionService;
import com.colabo.j2ee.web.oaf.security.IGrantService;
import com.colabo.j2ee.web.oaf.security.PermissionConstant;
import com.colabo.j2ee.web.oaf.vo.IPAuditLogVO;

/**
 * 增加组织数据过滤, 通过Service拦截实现
 */
public class UnitServiceImpl extends DefaultServiceImpl implements IUnitService {
	protected Log log = LogFactory.getLog(UnitServiceImpl.class);
	private static final String UNIT_SAVE_EXIST = "exist";
	private static final String UNIT_SAVE_SUCCESS = "true";
	private static final String UNIT_SAVE_FAILE = "false";
	private ILogDataService logDataService = null;
	private static final String MODEL_Name = AppConstants.MSG_INFO_APP_3003;

	public SCUnitProfileVO getUnitByUnitId(String unitid) throws ServiceException {
		if (unitid == null || "".equals(unitid)) {
			return null;
		}
		return (SCUnitProfileVO) super.findByID_Hibernate_Get(SCUnitProfileVO.class, unitid);
	}

	public List getUnitsBySuperUnit(SCUnitProfileVO superUnit) throws ServiceException {
		return getUnitsBySuperUnit(superUnit, 0, 9999);
	}

	public List getUnitsBySuperUnit(SCUnitProfileVO superUnit, int offset, int size) throws ServiceException {
		return getUnitsBySuperUnit(superUnit, new Boolean(false), offset, size);
	}

	public List getUnitsBySuperUnit(SCUnitProfileVO superUnit, Boolean delFlag, int offset, int pageSize)
			throws ServiceException {
		if (superUnit == null) {
			return super.find_iBatis("org.getRootUnits", null, offset, pageSize);
		}

		Map m = new HashMap();
		m.put("unitid", superUnit.getLogicalKey());
		if (delFlag != null) {
			m.put("delFlag", delFlag.booleanValue() ? SCUnitProfileVO.DEL_FLAG_DELETED : SCUnitProfileVO.DEL_FLAG_NORMAL);
		}
		return super.find_iBatis("org.getUnitsBySuperUnit", m, offset, pageSize);
	}

	public int getUnitCountBySuperUnit(SCUnitProfileVO superUnit) throws ServiceException {
		return getUnitCountBySuperUnit(superUnit, new Boolean(false));
	}

	public int getUnitCountBySuperUnit(SCUnitProfileVO superUnit, Boolean delFlag) throws ServiceException {
		List countList;
		if (superUnit == null) {
			countList = super.find_iBatis("org.getRootUnitCount", null);
		} else {
			Map m = new HashMap();
			m.put("unitid", superUnit.getLogicalKey());
			if (delFlag != null) {
				m.put("delFlag", delFlag.booleanValue() ? SCUnitProfileVO.DEL_FLAG_DELETED : SCUnitProfileVO.DEL_FLAG_NORMAL);
			}
			countList = super.find_iBatis("org.getUnitCountBySuperUnit", m);
		}
		if (!countList.isEmpty()) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}

	public String save(SCUnitProfileVO unitVo) throws ServiceException {
		IServerTime serverTime = (IServerTime) getBean(IServerTime.BEAN_ID);
		try {
			unitVo.setDelFlag(SCUnitProfileVO.DEL_FLAG_NORMAL);
			unitVo.setCreatedTimestamp(serverTime.getServerDateTime());
			checkUnit(unitVo);
		} catch (CommonException e) {
			return UNIT_SAVE_FAILE;
		}
		if (isExist(unitVo.getUnitCode())) {
			return UNIT_SAVE_EXIST;
		}
		super.save_Hibernate_Object(unitVo);
		SessionUserHolder suser = (SessionUserHolder) getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_SAVE, suser.getStaffId(),
				suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name) + IPAuditLogVO.SEPARATE + unitVo.getLogicalKey() + IPAuditLogVO.SEPARATE
						+ unitVo.getUnitName());
		return UNIT_SAVE_SUCCESS;
	}

	private void checkUnit(SCUnitProfileVO unitVo) {
		if (unitVo.getSupervisionUnit() != null) {
			String superUnitid = unitVo.getSupervisionUnit().getLogicalKey();
			if (superUnitid == null || "".equals(superUnitid)) {
				unitVo.setSupervisionUnit(null);
			}
		}

		if (unitVo.getFatherUnit() != null) {
			String ownerUnitid = unitVo.getFatherUnit().getLogicalKey();
			if (ownerUnitid == null || "".equals(ownerUnitid)) {
				unitVo.setFatherUnit(null);
			}
		}

		if (unitVo.getBizType() != null) {
			String bizType = unitVo.getBizType();
			if (bizType == null || "".equals(bizType)) {
				unitVo.setBizType(null);
			}
		}

		if (unitVo.getStatus() == null) {
			unitVo.setStatus(SCUnitProfileVO.STATUS_DEFAULT);
		}
		if (unitVo.getUnitType() == null) {
			unitVo.setUnitType(SCUnitProfileVO.KIND_DEFAULT);
		}
		if (unitVo.getDelFlag() == null) {
			unitVo.setDelFlag(SCUnitProfileVO.DEL_FLAG_NORMAL);
		}

	}

	public List save(List units) throws ServiceException {
		for (Iterator it = units.iterator(); it.hasNext();) {
			save((SCUnitProfileVO) it.next());
		}
		return units;
	}

	public void batchCommit(List insertBeans, List updateBeans, String delBeansStr) throws ServiceException {
		if (insertBeans != null) {
			for (Iterator it = insertBeans.iterator(); it.hasNext();) {
				save((SCUnitProfileVO) it.next());
			}
		}

		if (updateBeans != null) {
			for (Iterator it = updateBeans.iterator(); it.hasNext();) {
				update((SCUnitProfileVO) it.next());
			}
		}

		if (delBeansStr != null && !"".equals(delBeansStr)) {
			batchDelete(delBeansStr);
		}
	}

	private int batchDelete(String delBeansStr) throws ServiceException {
		super.update_iBatis("org.batchDeleteUnitsByUnitid", new Object[] { delBeansStr });
		SessionUserHolder suser = (SessionUserHolder) getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_BATCH, suser.getStaffId(),
				suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name));
		return 1;
	}

	public int delete(SCUnitProfileVO unit) throws ServiceException {
		// int count = getUnitCountBySuperUnit(unit);
		// if (count == 0) {
		if (delChildren(unit)) {
			// unit.setDelFlag(SCUnitProfileVO.DEL_FLAG_DELETED);
			// update(unit);
			SessionUserHolder suser = (SessionUserHolder) getBean("sessionUserHolder");
			if (SCUnitProfileVO.DEL_FLAG_DELETED.equals(unit.getDelFlag())) {
				logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_DELETE, suser
						.getStaffId(), suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name) + IPAuditLogVO.SEPARATE + unit.getLogicalKey()
						+ IPAuditLogVO.SEPARATE + unit.getUnitName());
			} else {
				logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_UPDATE, suser
						.getStaffId(), suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name) + IPAuditLogVO.SEPARATE + unit.getLogicalKey()
						+ IPAuditLogVO.SEPARATE + unit.getUnitName());
			}
			return 1;
		}
		// }
		return 0;
	}

	public int undelete(SCUnitProfileVO unit) throws ServiceException {
		unit.setDelFlag(SCUnitProfileVO.DEL_FLAG_NORMAL);
		update(unit);
		return 1;
	}

	public SCUnitProfileVO update(SCUnitProfileVO unitVo) throws ServiceException {
		IServerTime serverTime = (IServerTime) getBean(IServerTime.BEAN_ID);
		try {
			unitVo.setLastModifiedTimestamp(serverTime.getServerDateTime());
			checkUnit(unitVo);
		} catch (CommonException e) {
			throw new ServiceException(e);
		}
		super.update_Hibernate_Object(unitVo);
		SessionUserHolder suser = (SessionUserHolder) getBean("sessionUserHolder");
		if (SCUnitProfileVO.DEL_FLAG_DELETED.equals(unitVo.getDelFlag())) {
			logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_DELETE,
					suser.getStaffId(), suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name) + IPAuditLogVO.SEPARATE + unitVo.getLogicalKey()
							+ IPAuditLogVO.SEPARATE + unitVo.getUnitName());
		} else {
			logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_UPDATE,
					suser.getStaffId(), suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name) + IPAuditLogVO.SEPARATE + unitVo.getLogicalKey()
							+ IPAuditLogVO.SEPARATE + unitVo.getUnitName());
		}
		return unitVo;
	}
	
	/**
	 * 修改子节点treePath
	 * @param oldPath
	 * @param newPath
	 */
	public void updateChildTreePath(String oldPath, String newPath){
		//修改所有treePath中包含旧路径且路径不等于新路径中的所有数据，用最新的路径替换旧路径部分
		String sql = "UPDATE WF_UNIT SET TREE_PATH= replace(TREE_PATH,'" + oldPath + "','" + newPath + "') WHERE TREE_PATH LIKE '"
		+ oldPath + "%' and TREE_PATH<>'" + newPath + "'";
		try {
			this.update_JDBC(sql, null);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public SCUnitProfileVO getOwnerUnit(SCUnitProfileVO superUnit) throws ServiceException {
		if (superUnit.getFatherUnit() != null) {
			return superUnit.getFatherUnit();
		}

		SCUnitProfileVO ret = superUnit;
		while (!ret.getUnitType().equals(SCUnitProfileVO.KIND_ORG) && ret.getSupervisionUnit() != null) {
			ret = ret.getSupervisionUnit();
		}
		return ret.getUnitType().equals(SCUnitProfileVO.KIND_ORG) ? ret : null;
	}

	public int getUnitCountByOwnerUnit(SCUnitProfileVO ownerUnit) throws ServiceException {
		return getUnitCountByOwnerUnit(ownerUnit, new Boolean(false));
	}

	public List getUnitsByOwnerUnit(SCUnitProfileVO ownerUnit, int offset, int size) throws ServiceException {
		return getUnitsByOwnerUnit(ownerUnit, new Boolean(false), offset, size);
	}

	public int getUnitCountByOwnerUnit(SCUnitProfileVO ownerUnit, Boolean deleted) throws ServiceException {
		List countList;
		if (ownerUnit == null) {
			countList = super.find_iBatis("org.getRootUnitCount", null);
		} else {
			Map map = new HashMap();
			map.put("ownerUnitId", ownerUnit.getLogicalKey());
			if (deleted != null) {
				map.put("delFlag", deleted.booleanValue() ? RecordObject.DEL_FLAG_DELETED : RecordObject.DEL_FLAG_NORMAL);
			}
			countList = find_iBatis("org.getUnitCountByOwnerUnit", map);
		}
		if (countList != null && countList.size() > 0) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}

	public List getUnitsByOwnerUnit(SCUnitProfileVO ownerUnit, Boolean delFlag, int offset, int size) throws ServiceException {
		if (ownerUnit == null) {
			return super.find_iBatis("org.getRootUnits", null, offset, size);
		}
		Map map = new HashMap();
		map.put("ownerUnitId", ownerUnit.getLogicalKey());

		if (delFlag != null) {
			map.put("delFlag", delFlag.booleanValue() ? RecordObject.DEL_FLAG_DELETED : RecordObject.DEL_FLAG_NORMAL);
		}
		return super.find_iBatis("org.getUnitsByOwnerUnit", map, offset, size);
	}

	public List getUnitsByOwnerUnit(SCUnitProfileVO ownerUnit) throws ServiceException {
		return getUnitsByOwnerUnit(ownerUnit, 0, 9999);
	}

	public List getAllBizTypes() throws ServiceException {
		return findAll_Hibernate_Object(IPBizTypeVO.class);
	}

	public List findUnit(String unit, String direction, String offset) throws ServiceException {
		return null;
	}

	public boolean isExist(String unitcode) throws ServiceException {
		String sql = "from SCUnitProfileVO";
		HqlWrapper wrapper = new HqlWrapper();
		wrapper.setCondition("unitCode", HqlWrapper.EQUAL, unitcode);
		String[] propertyNames = StringUtil.listToStrArray(wrapper.getPropertyNames());
		String[] operators = StringUtil.listToStrArray(wrapper.getOperators());
		List valuesList = wrapper.getValues();
		Object[] values = valuesList == null || valuesList.size() == 0 ? null : valuesList.toArray();
		String orderBy = null;
		String groupBy = null;
		String otherCause = null;
		Object[] result = this.find_Hibernate_ComposedHQL(sql, propertyNames, operators, values, 0, 999999, true,
				orderBy, groupBy, otherCause);
		List l = (ArrayList) result[0];
		if (l.size() > 0) {
			return true;
		}
		return false;
	}

	public boolean delChildren(SCUnitProfileVO unit) throws ServiceException {
		String unitid = unit.getLogicalKey();
		if (!"".equals(unitid) && unitid != null) {

			HashMap hm = new HashMap();
			hm.put("unitid", unit.getLogicalKey());
			String now = DateTimeUtil.formatDateTime(DateTimeUtil.getDateTime());
			hm.put("lastModifyTime", now);
			// this.update_iBatis("org.deleteUnitByParent", new Object[] {
			// unitid });
			String sql = "UPDATE WF_UNIT SET DELFLAG='y',LastModifiedTime= '" + now + "' WHERE TREE_PATH LIKE '%"
					+ unit.getLogicalKey() + "%' or unitid='" + unit.getLogicalKey() + "'";
			this.update_JDBC(sql, null);
			SessionUserHolder suser = (SessionUserHolder) getBean("sessionUserHolder");
			logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_BATCH, suser.getStaffId(),
					suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name));
			return true;
		} else {
			return false;
		}
	}

	public long getMaxIndexNo() throws ServiceException {
		List list = this.find_iBatis("org.getUnitMaxIndexNo", new HashMap());
		if (list != null && list.size() > 0) {
			if (list.get(0) != null) {
				return new Long(list.get(0).toString()).longValue();
			}
		}
		return 0;
	}

	public ILogDataService getLogDataService() {
		return logDataService;
	}

	public void setLogDataService(ILogDataService logDataService) {
		this.logDataService = logDataService;
	}

	public List getAllUnits() throws ServiceException {
		// return super.find_iBatis("org.getAllUnitCount", null);
		List list = new ArrayList();
		List ret = find_iBatis("org.getAllUnit", new HashMap());
		if (ret == null) {
			return new ArrayList(0);
		}
		boolean isInformix = false;
		if(this.getDatabaseType().equals("informix")){
			isInformix = true;
		}
		
		if (ret != null) {
			for (int i = 0; i < ret.size(); i++) {
				HashMap hm = (HashMap) ret.get(i);
				if (hm != null) {

					SCUnitProfileVO vo = new SCUnitProfileVO();
					
					String unitid;
					String unitname;
					String unitcode;
					SCUnitProfileVO superUnit;//this.getUnitByUnitId(superunitid1);
					SCUnitProfileVO ownerUnit;//this.getUnitByUnitId(ownerunitid);
					String unitlevel;
					String areacode;
					String kind;
					String email;
					String status;
					String delflag;
					String issyn;
					String remark;
					String creatorid;
					Integer index_no;
					String tree_path;
					String tree_type;
					String tree_level;
					String tree_seq;
					String address;
					String telephone;
					String contactor;
					String effstarttime;
					String effendtime;
					String serverid;
					if (isInformix) {
						unitid = (String) hm.get("unitid");
						unitname = (String) hm.get("unitname");
						unitcode = (String) hm.get("unitcode");
						String superunitid1 = (String) hm.get("superunitid1");
						superUnit = new SCUnitProfileVO();
						superUnit.setLogicalKey(superunitid1);
						String ownerunitid = (String) hm.get("ownerunitid");
						ownerUnit = new SCUnitProfileVO();
						ownerUnit.setLogicalKey(ownerunitid);
						unitlevel = (String) hm.get("unitlevel");
						areacode = (String) hm.get("areacode");
						kind = (String) hm.get("kind");
						email = (String) hm.get("email");
						status = (String) hm.get("status");
						delflag = (String) hm.get("delflag");
						issyn = (String) hm.get("issyn");
						remark = (String) hm.get("remark");
						creatorid = (String) hm.get("creatorid");
						hm.get("createdtime");
						hm.get("lastmodifierid");
						hm.get("lastmodifiedtime");
						Object indexno = (Object) hm.get("index_no");
						index_no = Integer.valueOf((indexno == null ? "999999" : indexno.toString()));
						tree_path = (String) hm.get("tree_path");
						tree_type = (String) hm.get("tree_type");
						Object treeLevel = (Object) hm.get("tree_level");
						tree_level = treeLevel == null ? "1" : treeLevel.toString();
						tree_seq = (String) hm.get("tree_seq");
						address = (String) hm.get("address");
						telephone = (String) hm.get("telephone");
						contactor = (String) hm.get("contactor");
						effstarttime = (String) hm.get("effstarttime");
						effendtime = (String) hm.get("effendtime");
						serverid = (String) hm.get("serverid");
					} else {
						unitid = (String) hm.get("UNITID");
						unitname = (String) hm.get("UNITNAME");
						unitcode = (String) hm.get("UNITCODE");
						String superunitid1 = (String) hm.get("SUPERUNITID1");
						superUnit = new SCUnitProfileVO();
						superUnit.setLogicalKey(superunitid1);
						String ownerunitid = (String) hm.get("OWNERUNITID");
						ownerUnit = new SCUnitProfileVO();
						ownerUnit.setLogicalKey(ownerunitid);
						unitlevel = (String) hm.get("UNITLEVEL");
						areacode = (String) hm.get("AREACODE");
						kind = (String) hm.get("KIND");
						email = (String) hm.get("EMAIL");
						status = (String) hm.get("STATUS");
						delflag = (String) hm.get("DELFLAG");
						issyn = (String) hm.get("ISSYN");
						remark = (String) hm.get("REMARK");
						creatorid = (String) hm.get("CREATORID");
						hm.get("CREATEDTIME");
						hm.get("LASTMODIFIERID");
						hm.get("LASTMODIFIEDTIME");
						Object indexno = (Object) hm.get("INDEX_NO");
						index_no = Integer.valueOf((indexno == null ? "999999" : indexno.toString()));
						tree_path = (String) hm.get("TREE_PATH");
						tree_type = (String) hm.get("TREE_TYPE");
						Object treeLevel = (Object) hm.get("TREE_LEVEL");
						tree_level = treeLevel == null ? "1" : treeLevel.toString();
						tree_seq = (String) hm.get("TREE_SEQ");
						address = (String) hm.get("ADDRESS");
						telephone = (String) hm.get("TELEPHONE");
						contactor = (String) hm.get("CONTACTOR");
						effstarttime = (String) hm.get("EFFSTARTTIME");
						effendtime = (String) hm.get("EFFENDTIME");
						serverid = (String) hm.get("SERVERID");
					}
					vo.setLogicalKey(unitid);
					vo.setUnitName(unitname);
					vo.setUnitCode(unitcode);
					vo.setSupervisionUnit(superUnit);
					vo.setFatherUnit(ownerUnit);
					vo.setUnitLevel(unitlevel);
					vo.setLocationCode(areacode);
					vo.setUnitType(kind);
					//vo.setBizType(biztype);
					vo.setPublicEmail(email);
					vo.setStatus(status);
					vo.setDelFlag(delflag);
					vo.setIsSyn(issyn);
					vo.setRemark(remark);
					vo.setIndexNo(index_no);
					vo.setCreatorId(creatorid);
					//vo.setCreatedTime(createdtime);
					vo.setTreePath(tree_path);
					vo.setTreeLevel(tree_level);
					vo.setAddress(address);
					vo.setTelephone(telephone);

					list.add(vo);
				}
			}
		}

		return list;
		
	}
	
	
	
	
	public String getDatabaseType() throws ServiceException {
		String dbName = "";
		Connection conn = null;
		try {

			conn = getJdbcTemplate().getDataSource().getConnection();
			String driverName = conn.getMetaData().getDriverName().toLowerCase();
			if (driverName.indexOf("oracle") != -1) {
				dbName = "oracle";
			} else if (driverName.indexOf("informix") != -1) {
				dbName = "informix";
			} else if (driverName.indexOf("sqlserver") != -1) {
				dbName = "sqlserver";
			} else if (driverName.indexOf("sybase") != -1) {
				dbName = "sybase";
			} else if (driverName.indexOf("db2") != -1) {
				dbName = "db2";
			} else if (driverName.indexOf("mysql") != -1) {
				dbName = "mysql";
			} else {
				dbName = "oracle";
			}

		} catch (ServiceException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
				throw new ServiceException(e);
			}
		}

		return dbName;
	}
	public List getAllChildUnitByUnitId(String unitId) throws ServiceException {
		
		//return super.find_iBatis("org.getAllUnitCount", null);
		HashMap paras = new HashMap();
		paras.put("unitid", unitId);
		List list = new ArrayList();
		List ret = find_iBatis("org.getAllChildUnitByUnitId", paras);
		if (ret == null) {
			return new ArrayList(0);
		}

		boolean isInformix = false;
		if(this.getDatabaseType().equals("informix")){
			isInformix = true;
		}
		
		if (ret != null) {
			for (int i = 0; i < ret.size(); i++) {
				HashMap hm = (HashMap) ret.get(i);
				if (hm != null) {

					SCUnitProfileVO vo = new SCUnitProfileVO();

					String unitid;
					String unitname;
					String unitcode;
					SCUnitProfileVO superUnit;//this.getUnitByUnitId(superunitid1);
					SCUnitProfileVO ownerUnit;//this.getUnitByUnitId(ownerunitid);
					String unitlevel;
					String areacode;
					String kind;
					String email;
					String status;
					String delflag;
					String issyn;
					String remark;
					String creatorid;
					Integer index_no;
					String tree_path;
					String tree_type;
					String tree_level;
					String tree_seq;
					String address;
					String telephone;
					String contactor;
					String effstarttime;
					String effendtime;
					String serverid;
					if (isInformix) {
						unitid = (String) hm.get("unitid");
						unitname = (String) hm.get("unitname");
						unitcode = (String) hm.get("unitcode");
						String superunitid1 = (String) hm.get("superunitid1");
						superUnit = new SCUnitProfileVO();
						superUnit.setLogicalKey(superunitid1);
						String ownerunitid = (String) hm.get("ownerunitid");
						ownerUnit = new SCUnitProfileVO();
						ownerUnit.setLogicalKey(ownerunitid);
						unitlevel = (String) hm.get("unitlevel");
						areacode = (String) hm.get("areacode");
						kind = (String) hm.get("kind");
						email = (String) hm.get("email");
						status = (String) hm.get("status");
						delflag = (String) hm.get("delflag");
						issyn = (String) hm.get("issyn");
						remark = (String) hm.get("remark");
						creatorid = (String) hm.get("creatorid");
						hm.get("createdtime");
						hm.get("lastmodifierid");
						hm.get("lastmodifiedtime");
						Object indexno = (Object) hm.get("index_no");
						index_no = Integer.valueOf((indexno == null ? "999999" : indexno.toString()));
						tree_path = (String) hm.get("tree_path");
						tree_type = (String) hm.get("tree_type");
						Object treeLevel = (Object) hm.get("tree_level");
						tree_level = treeLevel == null ? "1" : treeLevel.toString();
						tree_seq = (String) hm.get("tree_seq");
						address = (String) hm.get("address");
						telephone = (String) hm.get("telephone");
						contactor = (String) hm.get("contactor");
						effstarttime = (String) hm.get("effstarttime");
						effendtime = (String) hm.get("effendtime");
						serverid = (String) hm.get("serverid");
					} else {
						unitid = (String) hm.get("UNITID");
						unitname = (String) hm.get("UNITNAME");
						unitcode = (String) hm.get("UNITCODE");
						String superunitid1 = (String) hm.get("SUPERUNITID1");
						superUnit = new SCUnitProfileVO();
						superUnit.setLogicalKey(superunitid1);
						String ownerunitid = (String) hm.get("OWNERUNITID");
						ownerUnit = new SCUnitProfileVO();
						ownerUnit.setLogicalKey(ownerunitid);
						unitlevel = (String) hm.get("UNITLEVEL");
						areacode = (String) hm.get("AREACODE");
						kind = (String) hm.get("KIND");
						email = (String) hm.get("EMAIL");
						status = (String) hm.get("STATUS");
						delflag = (String) hm.get("DELFLAG");
						issyn = (String) hm.get("ISSYN");
						remark = (String) hm.get("REMARK");
						creatorid = (String) hm.get("CREATORID");
						hm.get("CREATEDTIME");
						hm.get("LASTMODIFIERID");
						hm.get("LASTMODIFIEDTIME");
						Object indexno = (Object) hm.get("INDEX_NO");
						index_no = Integer.valueOf((indexno == null ? "999999" : indexno.toString()));
						tree_path = (String) hm.get("TREE_PATH");
						tree_type = (String) hm.get("TREE_TYPE");
						Object treeLevel = (Object) hm.get("TREE_LEVEL");
						tree_level = treeLevel == null ? "1" : treeLevel.toString();
						tree_seq = (String) hm.get("TREE_SEQ");
						address = (String) hm.get("ADDRESS");
						telephone = (String) hm.get("TELEPHONE");
						contactor = (String) hm.get("CONTACTOR");
						effstarttime = (String) hm.get("EFFSTARTTIME");
						effendtime = (String) hm.get("EFFENDTIME");
						serverid = (String) hm.get("SERVERID");
					}

					vo.setLogicalKey(unitid);
					vo.setUnitName(unitname);
					vo.setUnitCode(unitcode);
					vo.setSupervisionUnit(superUnit);
					vo.setFatherUnit(ownerUnit);
					vo.setUnitLevel(unitlevel);
					vo.setLocationCode(areacode);
					vo.setUnitType(kind);
					// vo.setBizType(biztype);
					vo.setPublicEmail(email);
					vo.setStatus(status);
					vo.setDelFlag(delflag);
					vo.setIsSyn(issyn);
					vo.setRemark(remark);
					vo.setIndexNo(index_no);
					vo.setCreatorId(creatorid);
					// vo.setCreatedTime(createdtime);
					vo.setTreePath(tree_path);

					vo.setTreeLevel(tree_level);
					vo.setAddress(address);
					vo.setTelephone(telephone);

					list.add(vo);
				}
			}
		}

		return list;
	}
	public List queryUnit(HashMap map) throws ServiceException {
		return super.find_iBatis("org.queryUnit", map);
	}
	/**
	 * 获取指定ｉｄ的所有子组织机构
	 * @param unitId　
	 * @return
	 * @throws ServiceException
	 */
	public List getAllUnitByPosition(String uintId) throws ServiceException {		
		IPCodeInfoVO codeinfo = CodeInfoCache.newInstance().getCodeInfoVO("SystemConfiguration", "enable_data_permission");
		SessionUserHolder sh = (SessionUserHolder) getBean("sessionUserHolder");
		IGrantService grantService = (IGrantService) getBean(IGrantService.BEAN_ID);
		
		List list = new ArrayList();
		
		if(grantService.isAdmin(sh.getStaffId())||codeinfo==null||(!"true".equalsIgnoreCase(codeinfo.getCodeinfoValue()))){			
			if(uintId==null){
				return UnitCache.getInstance().getUnitsBySuperUnit(null);
			}else{
				UnitCache.getInstance().getUnitByUnitId(uintId);
				list.addAll(UnitCache.getInstance().getDefaultChildUnits());
				return list;
			}
		}else{
			
			
			IDataPermissionService dps = (IDataPermissionService)getBean(IDataPermissionService.BEAN_ID);	
			
			if(uintId==null){			
				List rsList = dps.findUnit(sh.getStaffId(), null, PermissionConstant.UP_DIRECTION_DOWN_ALL);
				if(rsList==null||rsList.size()<1){
					return new ArrayList();
				}
				return processRoot(rsList);				
			}else{
						
				List rsList = dps.findUnit(sh.getStaffId(), null, PermissionConstant.UP_DIRECTION_DOWN_ALL);
				
				if(rsList==null||rsList.size()<1){
					return new ArrayList();
				}
				return processRoot(rsList);		
			}			
		}		
	}
	
	private List processRoot(List list){
		List aList = new ArrayList();
		//处理父亲结点
	   	for (int i = 0; i < list.size(); i++) {
			SCUnitProfileVO temp = (SCUnitProfileVO) list.get(i);
			if(temp.getSupervisionUnit()!=null){				
				if (!isExist(temp.getSupervisionUnit().getLogicalKey(),list)){
				   temp.setSupervisionUnit(null);
				}
			}
			aList.add(temp);
	   	}
	   	
		return aList;
	}
	
	/**
	 * 判断是否存在
	 * @param unitid　单位ｉｄ
	 * @param l 单位列表
	 * @return
	 */
	public boolean isExist(String unitid,List l){					
	  	for (int i = 0; i < l.size(); i++) {					
	  		SCUnitProfileVO temp = (SCUnitProfileVO) l.get(i);
	  		if(unitid.trim().equals(temp.getLogicalKey().trim())){
				return true;							  
			}			
		}			
	   return false;
	}

	public List queryBackUnit(HashMap map, int offset, int pageSize) throws ServiceException {
		return super.find_iBatis("org.queryBackUnit", map, offset, pageSize);
	}
	
	public int queryBackUnitCount(HashMap map) throws ServiceException {
		List countList = super.find_iBatis("org.queryBackUnitCount", map);
		
		if (!countList.isEmpty()) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}
	
	public String saveBackToUnit(List backBeans) throws ServiceException ,CommonException{
		int result = 0;
		
		if (backBeans != null) {
			for (Iterator it = backBeans.iterator(); it.hasNext();) {
				SCUnitProfileVO ips = (SCUnitProfileVO) it.next();	
				updateBackUnit(ips);			
				result++;
			}
		}
		return "true";
	}
	
	public String saveFullDel(List delBeans) throws ServiceException ,CommonException{
		int result = 0;
		
		if (delBeans != null) {
			for (Iterator it = delBeans.iterator(); it.hasNext();) {
				SCUnitProfileVO ips = (SCUnitProfileVO) it.next();	
				delFullStaff(ips);
				result++;
			}
		}
		return "true";
	}

	private void updateBackUnit(SCUnitProfileVO ips) throws ServiceException,
			CommonException {
		//super.update_iBatis("org.undeleteUnitByUnitid", new Object[] { ips.getLogicalKey() });
		String now = DateTimeUtil.formatDateTime(DateTimeUtil.getDateTime());
		String sql = "UPDATE WF_UNIT SET DELFLAG='n',LastModifiedTime= '" + now + "' WHERE TREE_PATH LIKE '%"
				+ ips.getLogicalKey() + "%' or unitid='" + ips.getLogicalKey() + "'";
		this.update_JDBC(sql, null);
		SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_UPDATE, suser.getStaffId(), suser
				.getLoginIp(), PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3002) + IPAuditLogVO.SEPARATE + ips.getLogicalKey()+IPAuditLogVO.SEPARATE+ips.getUnitName());
	}
	
	private void delFullStaff(SCUnitProfileVO ips) throws ServiceException,
			CommonException {
		ips.setSupervisionUnit(null);
		ips.setFatherUnit(null);
		super.delete_Hibernate_Object(ips);
		SessionUserHolder suser = (SessionUserHolder) getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN, IPAuditLogVO.OP_CODE_DELETE, suser.getStaffId(),
				suser.getLoginIp(), PropertyUtil.getPropertyByKey(MODEL_Name));
	}
	
	public List queryUnit(HashMap map, int offset, int pageSize) throws ServiceException {
		return super.find_iBatis("org.queryUnit", map, offset, pageSize);
	}
	
	public int queryUnitCount(HashMap map) throws ServiceException{
		List countList = super.find_iBatis("org.queryUnitCount", map);
		
		if (!countList.isEmpty()) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}
}
